package com.fxu.role.api;

import cn.hutool.core.util.StrUtil;
import com.fxu.framework.core.base.Result;
import com.fxu.framework.core.exception.MsgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * web socket 服务端
 * @author fangxu
 * @version 2022-03-02
 */
@Slf4j
@Component
@ServerEndpoint("/webSocket/{api}/{uid}")
public class WebSocketServer {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收的API, 指名哪个API接口
     */
    private String api = "";

    /**
     * 接收uid, 指名哪个用户
     */
    private String uid = "";

    /**
     * 连接建立成功调用的方法
     * @param session 连接对象
     * @param api 接口名
     * @param uid 唯一表示
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("api") String api, @PathParam("uid") String uid) {
        log.info("接到来自[/webSocket/" + api + "/" + uid + "]的链接");
        //如果存在就先删除一个，防止重复推送消息
        for (WebSocketServer webSocket : webSocketSet) {
            if (webSocket.api.equals(api) && webSocket.uid.equals(uid)) {
                webSocketSet.remove(webSocket);
            }
        }
        this.session = session;
        this.api = api;
        this.uid = uid;
        webSocketSet.add(this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("接到来自[/webSocket/" + api + "/" + uid + "]的关闭连接请求");
        webSocketSet.remove(this);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 连接对象
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自[/webSocket/" + api + "/" + uid + "]的信息:" + message);
        // =>测试回复消息 => 调用业务逻辑
        try {
            this.sendMessage(message);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送消息
     * @param api 接口名
     * @param uid 用户ID
     * @param message 消息
     * @return 发送信息
     */
    public static Result<String> sendMessage(String api, String uid, String message) {
        log.info("推送消息到[/webSocket/" + api + "/" + uid + "]，推送内容:" + message);
        if (StrUtil.isEmpty(api) || StrUtil.isEmpty(message)) {
            throw new MsgException("入参错误!api=" + api + ",message=" + message);
        }
        for (WebSocketServer item : webSocketSet) {
            // uid = null 全体用户发送, uid != null 单个用户[uid]发送
            if (api.equals(item.api) && (StrUtil.isEmpty(uid) || item.uid.equals(uid))) {
                try {
                    item.sendMessage(message);
                } catch (IOException ignored) {
                    log.error("web socket send message error!{}", ignored.getMessage());
                    // return Result.error(ignored.getMessage());
                }
            }
        }
        return Result.ok("成功");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketServer that = (WebSocketServer) o;
        return Objects.equals(session, that.session) && Objects.equals(api, that.api) && Objects.equals(uid, that.uid);
    }

    @Override
    public int hashCode() {
        return Objects.hash(session, api, uid);
    }
}